//
//  HTTPrequest.m
//  PeanutEbuy
//
//  Created by 赵甜 on 2020/4/26.
//  Copyright © 2020 赵甜. All rights reserved.
//

#import "HTTPrequest.h"

#define RIGHT_CODE 200
#define CODE_KEY @"code"
#define CONTENT_KEY @"result"
#define MESSAGE_KEY @"errordes"



@implementation HTTPrequest
DEF_SINGLETON(HTTPrequest)
//城市接口
-(void)getCitylist_success:(void (^_Nonnull)(NSDictionary *dic))success
           failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    NSString *methed = @"GET";
    NSString *path = @"/common/region/findAllData";
    
    [self HttpRequstmethed:methed path:path parameters:nil success:success failure_Nonnull:failure];
}

//获取验证码
-(void)getCodeByPhoneNum:(NSString *)phoneNum
                 success:(void (^_Nonnull)(NSDictionary *dic))success
         failure_Nonnull:(void (^_Nonnull)(NSDictionary *dic))failure{
    NSString *methed = @"POST";
    NSString *path = @"/login/sms/verification-code";
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:phoneNum forKey:@"mobile"];
//        NSString * jsonStr =[self convertToJsonData:dic];
    
    [self HttpRequstmethed:methed path:path parameters:dic success:success failure_Nonnull:failure];
}


//登录获取token
-(void)getMobileToken:(NSString *_Nullable)phoneNum
              smsCode:(NSString *_Nullable)smsCode
              success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
      failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    NSString *methed = @"POST";
    NSString *path = @"/user/login/mobile-token";

    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:phoneNum forKey:@"mobile"];
    [dic setObject:smsCode forKey:@"smsVerificationCode"];
    
    [self HttpRequstmethed:methed path:path parameters:dic success:success failure_Nonnull:failure];
}


//轮播图广告接口
-(void)getAdvImage:(int)place
        success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    NSString *methed = @"GET";
    NSString *path = @"/app/adverts/info/";
    
    path = [NSMutableString stringWithFormat:@"%@%d",path,place];
    
    [self HttpRequstmethed:methed path:path parameters:nil success:success failure_Nonnull:failure];
}


//用户点击App广告
-(void)clickAdvImage:(int)imgId
        success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
     failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
        NSString *methed = @"GET";
        NSString *path = @"/app/adverts/click/";
        
        path= [NSMutableString stringWithFormat:@"%@%d",path,imgId];
        
    [self HttpRequstmethed:methed path:path parameters:nil success:success failure_Nonnull:failure];
}
#pragma mark - 商品搜索
//商品搜索记录
-(void)http_mySearchHistory_success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
                    failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    NSString *methed = @"POST";
    NSString *path = @"/app/goods/mySearchHistory";
    
    [self HttpRequstmethed:methed path:path parameters:nil success:success failure_Nonnull:failure];
}

//清空搜索记录
-(void)http_clearSearchHistory_success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
                       failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    NSString *methed = @"POST";
    NSString *path = @"/app/goods/clearSearchHistory";
    
    [self HttpRequstmethed:methed path:path parameters:nil success:success failure_Nonnull:failure];
}
//商品搜索
-(void)search_Goods:(NSString *_Nullable)keyword//商品关键字
             orderBy:(NSString *_Nullable)orderBy//排序综合:common,销量:sale,价格price,默认common
           ascOrDesc:(NSString *_Nullable)ascOrDesc
             pageNum:(int)pageNum
            pageSize:(int)pageSize
        success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
     failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    NSString *methed = @"POST";
    NSString *path = @"/app/goods/pageInfo";
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject: keyword forKey:@"keyword"];
    [dic setObject: orderBy forKey:@"orderBy"];
    [dic setObject: ascOrDesc forKey:@"ascOrDesc"];
    [dic setObject:[NSNumber numberWithInt:pageNum] forKey:@"pageNum"];
    [dic setObject:[NSNumber numberWithInt:pageSize] forKey:@"pageSize"];
    
    [self HttpRequstmethed:methed path:path parameters:dic success:success failure_Nonnull:failure];
    
}

#pragma mark - 商品相关
-(void)get_Goods_Type_map:(int)goodsType
                    level:(int)level
                    parentId:(int)parentId
        success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
          failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
        NSString *methed = @"GET";
        NSString *path = @"/app/goods-cate/map";
        
    //    NSMutableString * urlStr = [NSMutableString stringWithFormat:@"%@%d",path,imgId];
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:[NSNumber numberWithInt:goodsType] forKey:@"goodsType"];
        [dic setObject:[NSNumber numberWithInt:level] forKey:@"level"];
        [dic setObject:[NSNumber numberWithInt:parentId] forKey:@"parentId"];

    [self HttpRequstmethed:methed path:path parameters:dic success:success failure_Nonnull:failure];
}




//商品详情
-(void)get_Goods_Detail_BygoodsNo:(NSString * _Nonnull )goodsNo
                          success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
                  failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    NSString *methed = @"POST";
    NSString *path = @"/app/goods/detail";
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
      [dic setObject: goodsNo forKey:@"goodsNo"];
    [self HttpRequstmethed:methed path:path parameters:dic success:success failure_Nonnull:failure];
}

#pragma mark - 回收
//查询回收分类列表
-(void)recycle_Gategory_List_success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
                     failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    
    NSString *methed = @"GET";
    NSString *path = @"/app/recycle/category/map";
        
    [self HttpRequstmethed:methed path:path parameters:nil success:success failure_Nonnull:failure];
}

//查询回收品牌列表
-(void)recycle_brand_list:(int)cateId//分类
                  success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
          failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    NSString *methed = @"GET";
    NSString *path = @"/app/recycle/brand/map/";
    
    path = [NSMutableString stringWithFormat:@"%@%d",path,cateId];
    [self HttpRequstmethed:methed path:path parameters:nil success:success failure_Nonnull:failure];
}

//回收型号列表
-(void)recycle_model_list:(int)cateId
                  brandId:(int)brandId//品牌
                  success:(void (^_Nonnull)(NSDictionary * _Nullable dic))success
          failure_Nonnull:(void (^_Nonnull)(NSDictionary * _Nonnull dic))failure{
    
    NSString *methed = @"GET";
    NSString *path = @"/app/recycle/model/map";
    
//    NSMutableString * urlStr = [NSMutableString stringWithFormat:@"%@%d",path,imgId];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[NSNumber numberWithInt:cateId] forKey:@"cateId"];
    [dic setObject:[NSNumber numberWithInt:brandId] forKey:@"brandId"];
        
    [self HttpRequstmethed:methed path:path parameters:dic success:success failure_Nonnull:failure];
}



-(void)HttpRequstmethed:(NSString *)methed
                path:(NSString *)path
             parameters:(NSDictionary *)paramedic
                success:(void (^_Nonnull)(NSDictionary *dic))success
        failure_Nonnull:(void (^_Nonnull)(NSDictionary *dic))failure{
    
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",HTTP_API,path];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer    = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    // 设置超时时间
    manager.requestSerializer.timeoutInterval = 30.0f;
    [manager.requestSerializer setValue:[ZTCore getUsertoken] forHTTPHeaderField:@"PEANUT-AUTH-TOKEN"];

        
    if ([methed isEqualToString:@"POST"]) {
        [manager POST:urlStr parameters:paramedic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            int code = [[responseObject objectForKey:CODE_KEY]intValue];
            if (code == RIGHT_CODE) {
                if ([responseObject isKindOfClass:[NSDictionary class]]==YES) {
                    success(responseObject);
                }else{
                    ZTLog(@"请求结果：%@ .",[self convertToJsonData:[responseObject objectForKey:@"message"]]);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            ZTLog(@"失败");
        }];
    }else{
        [manager GET:urlStr parameters:paramedic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            int code = [[responseObject objectForKey:CODE_KEY]intValue];
                if (code == RIGHT_CODE) {
                    if ([responseObject isKindOfClass:[NSDictionary class]]==YES) {
                        success(responseObject);
                    }
//                    ZTLog(@"请求结果：%@ .",[responseObject objectForKey:@"message"]);
                }
            ZTLog(@"请求结果：%@ .",[responseObject objectForKey:@"message"]);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            ZTLog(@"失败");
        }];
    }
}



-(NSString *)convertToJsonData:(NSDictionary *)dict

{

    NSError *error;



    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString;

    if (!jsonData) {

        NSLog(@"%@",error);

    }else{

        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    //去掉字符串中的空格

    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRange range2 = {0,mutStr.length};

    //去掉字符串中的换行符

    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;

}
@end
